package com.jl.smartcard.ui.views.filesystem;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.jl.card.CardManager;
import com.jl.card.file.CardFile;
import com.jl.smartcard.ui.ActivatorUI;
import com.jl.smartcard.ui.ImageShop;
import com.jl.smartcard.ui.SmartCardUI;
import com.jl.smartcard.ui.editors.cardfile.CardFileEditor;
import com.jl.smartcard.ui.editors.cardfile.CardFileEditorInput;

public class CardFileSystemView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "com.jl.core.views.CardFileSystemView";

	private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action searchAll;
	private Action doubleClickAction;
	/**a state to check the viewer is in searching state*/
	private boolean isSearching = false;

	private File filesys;
	
	private Object input;

	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public CardFileSystemView() {
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	@Override
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setContentProvider(new ViewContentProvider(this));
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem()
				.setHelp(viewer.getControl(), "com.jl.core.viewer");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
		if(input != null){
			viewer.setInput(input);
			viewer.refresh();
			viewer.expandAll();
		}
	}
	
	@Override
	public void init(IViewSite site, IMemento memento) throws PartInitException {
		super.init(site, memento);
		
		IPath syspath = ActivatorUI.getDefault().getStateLocation().append("filesystem.dat");
		this.filesys = syspath.toFile();
		if(filesys.exists()){
			ObjectInputStream ois;
			try {
				ois = new ObjectInputStream(new FileInputStream(filesys));
				this.input = ois.readObject();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				this.input = null;
			}
		}
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			@Override
			public void menuAboutToShow(IMenuManager manager) {
				CardFileSystemView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(searchAll);
		manager.add(new Separator());
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(searchAll);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		searchAll = new Action() {
			@Override
			public void run() {
				doSearchAll();
			}
		};

		searchAll.setText("Search Under MF");
		searchAll
				.setToolTipText("Search Under MF,it will auto seacch the card last connect");
		searchAll.setImageDescriptor(ImageShop.getDescriptor("search_mf_16"));

		doubleClickAction = new Action() {
			@Override
			public void run() {
				doDoubleClick();
			}
		};
	}

	protected void doDoubleClick() {
		
		if(CardManager.getInstance().getLastConnectCard() == null){
			MessageBox message = new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.ERROR);
			message.setText("Error");
			message.setMessage("please connect a card first!!!");
			message.open();
			return;
		}
		
		ISelection selection = viewer.getSelection();
		final Object obj = ((IStructuredSelection) selection).getFirstElement();
		if (obj instanceof TreeDF) {
			if (isSearching) {
				return;
			}
			isSearching = true;
			Job job = new Job("Serch Under " + ((TreeDF) obj).getName()) {
				@Override
				protected IStatus run(IProgressMonitor monitor) {
					FileSystemEntityFactory.loopThisDF((TreeDF) obj,monitor);
					monitor.done();
					getSite().getShell().getDisplay().asyncExec(new Runnable() {
						@Override
						public void run() {
							viewer.refresh();
							viewer.expandAll();
						}
					});
					isSearching = false;
					return Status.OK_STATUS;
				}
			};
			job.setUser(true);
			job.schedule();
		} else if (obj instanceof TreeEF) {
			if (isSearching) {
				return;
			}
			openCardFileEditor((TreeEF) obj);
		}
	}

	protected void doSearchAll() {
		if (isSearching) {
			return;
		}
		isSearching = true;
		Job job = new Job("Serch Under MF") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				final Object obj = FileSystemEntityFactory.setNavigatorEntity(monitor);
				getSite().getShell().getDisplay().asyncExec(new Runnable() {
					@Override
					public void run() {
						viewer.setInput(obj);
						viewer.refresh();
						viewer.expandAll();
					}
				});
				isSearching = false;
				return Status.OK_STATUS;
			}
		};
		job.setUser(true);
		job.schedule();
	}

	/**
	 * 
	 * @param obj
	 */
	protected void openCardFileEditor(TreeEF ef) {
		CardFile file = ef.getCardFile();
		String name = file.path();
		CardFileEditorInput input = new CardFileEditorInput(name);
		CardFileEditor editor = null;
		try {
			editor = (CardFileEditor) PlatformUI.getWorkbench()
					.getActiveWorkbenchWindow().getActivePage()
					.openEditor(input, SmartCardUI.ID_EDITOR_CARDFILE, true);
		} catch (PartInitException e) {
			e.printStackTrace();
			return;
		}
		editor.setCardFile(file);

	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			@Override
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	@Override
	public void setFocus() {
		viewer.getControl().setFocus();
	}
	
	@Override
	public void saveState(IMemento memento) {
		super.saveState(memento);
		List<?> temp = (List<?>) viewer.getInput();
		if(temp == null || temp.size() == 0){
			return;
		}else{
			try {
				if(!filesys.exists()){
					filesys.createNewFile();
				}
				ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filesys));
				oos.writeObject(temp);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}